# -*- coding:utf-8 -*-
# @File       :   handle_js.py
# @Author     :   LINING
# @Time       :   2024/7/25 16:19
# @Description : js操作封装
from Core.pageOpt import Page
from Handle.handle_log import log


def get_session_storage(page):
    """
    获取sessionStorage值
    :return:
    """
    try:
        value = Page(page).page_execute_script("window.sessionStorage;")
        return str(value)
    except Exception as e:
        log.log_error(f"获取sessionStorage值失败：{str(e)}")


def set_session_storage(page, key):
    """
    设置sessionStorage值
    :param page:
    :param key:传字典
    :return:
    """
    try:
        key = dict(key)
        for k, v in key.items():
            Page(page).page_execute_script(f"sessionStorage.setItem({k}, {v})")
    except Exception as e:
        log.log_error(f"设置sessionStorage值失败：{str(e)}")


def get_local_storage(page):
    """
    获取localStorage值
    :return:
    """
    try:
        value = Page(page).page_execute_script("window.localStorage;")
        return str(value)
    except Exception as e:
        log.log_error(f"获取localStorage值失败：{str(e)}")


def set_local_storage(page, key):
    """
    设置localStorage值
    :param page:
    :param key:传字典
    :return:
    """
    try:
        key = dict(key)
        for k, v in key.items():
            Page(page).page_execute_script(f"localStorage.setItem({k}, {v})")
    except Exception as e:
        log.log_error(f"设置localStorage值失败：{str(e)}")


def get_cookies(page):
    """
    获取cookies值
    :return:
    """
    try:
        value = Page(page).page_execute_script("document.cookie;")
        return str(value)
    except Exception as e:
        log.log_error(f"获取cookies值失败：{str(e)}")


def set_cookies(page, key):
    """
    设置cookies值
    :param page:
    :param key:字符串
    :return:
    """
    try:
        cookie = {}
        if isinstance(key, dict):
            cookie = key
        elif isinstance(key, str):
            key = key.split(';')
            for i in key:
                cookie[i.split('=')[0]] = i.split('=')[1]
        for k,v in cookie.items():
            Page(page).page_execute_script(f"document.cookie='{k}={v}'")
    except Exception as e:
        log.log_error(f"设置cookies值失败:{repr(e)}")


def skip_reptile(page):
    """
    跳过爬虫
    :param page:
    :return:
    """
    try:
        js = "Object.defineProperties(navigator, {webdriver:{get:()=>undefined}});"
        Page(page).page_execute_script(js)
        log.log_info(f"执行跳过爬虫js成功")
    except Exception as e:
        log.log_error(f"跳过爬虫失败：{str(e)}")


if __name__ == '__main__':
    from Handle.handle_yaml import token_file
    a = {}
    with open(token_file+'_user', 'r') as f:
        cookie = f.read()
    if isinstance(cookie, dict):
        cookie = cookie
    elif isinstance(cookie, str):
        key = cookie.split(';')
        for i in key:
            a[i.split('=')[0]] = i.split('=')[1]
    print(a)